<template>
  <a-modal
    v-model:open="visible"
    centered
    :title="modalTitle"
    width="600px"
    :confirm-loading="confirmLoading"
    :body-style="{ paddingLeft: '0', paddingRight: '0' }"
    :footer="showFooter"
    @ok="onSubmit"
    @cancel="onClose"
  >
    <a-form ref="formRef" class="px-32" :model="formState" layout="vertical" name="teacherForm" autocomplete="off" :rules="rules">
      <a-form-item label="邀请加入的班级" name="orgId">
        <a-tree-select
          v-model:value="formState.orgId"
          :loading="organizationOptionsLoading"
          tree-default-expand-all
          :tree-data="treeData"
          placeholder="请选择班级"
          :show-checked-strategy="TreeSelect.SHOW_ALL"
          @change="treeSelectChange"
        >
          <!-- <template #title="{ label }">
            <span :title="label">{{ label }}</span>
          </template> -->
        </a-tree-select>
      </a-form-item>

      <a-form-item label="教师审核" name="authType">
        <a-radio-group v-model:value="formState.authType" :options="options" @change="authTypeChange" />
      </a-form-item>
    </a-form>

    <div v-if="showFooter === null" class="invitation-card-wrap">
      <div class="header">
        <div class="title-wrap">
          <p>邀请链接</p>
          <!-- <div v-if="true" class="tag-wrap">有效</div>
          <div v-else class="tag-wrap invalid">失效</div> -->
        </div>
        <div class="flex gap-x-4">
          <!-- <template> -->
          <a-button size="small" :loading="inviteLinkLoading" @click="handleInvalid">删除链接</a-button>
          <a-button class="icon-with-btn" size="small" type="primary" @click="copyLink">
            <i class="iconfont icon-link-m"></i>
            复制链接
          </a-button>
          <!-- </template> -->
          <!-- <template v-else>
            <a-button size="small" @click="onSubmit">重新生成</a-button>
          </template> -->
        </div>
      </div>
      <div class="content-wrap">
        {{ inviteLink }}
      </div>
    </div>

    <template #footer>
      <!-- <a-button @click="onClose">取消</a-button> -->
      <a-button type="primary" :loading="confirmLoading" @click="onSubmit">生成链接</a-button>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
  import { message, RadioGroupProps, TreeSelect } from 'ant-design-vue'
  import type { Rule } from 'ant-design-vue/es/form'
  import { TreeSelectProps } from 'ant-design-vue/es/tree-select'
  import { reactive, ref, watch } from 'vue'
  import { useRequest } from 'vue-request'

  import { useModalForm } from '@/hooks/use-modal-form'
  import { studentsManageApi, teacherManageApi } from '@/services/api/aigc-admin'
  import { copyText } from '@/utils'

  interface FormState {
    id?: string
    orgId?: string
    authType?: boolean
  }

  const emits = defineEmits<{
    (e: 'submit', state: FormState): void
    (e: 'close'): void
  }>()

  const rules: Record<string, Rule[]> = {
    orgId: [{ required: true, message: '请选择班级', trigger: 'change' }],
    authType: [{ required: true, message: '请选择是否审核', trigger: 'change' }]
  }

  const formState = reactive<FormState>({
    orgId: undefined,
    authType: true
  })

  const inviteLink = ref<string>('')
  // 用于控制底部按钮的显示 为null时不显示 为undefined时显示
  const showFooter = ref<null | undefined>(undefined)

  const options = ref<RadioGroupProps['options']>([
    {
      value: true,
      label: '是'
    },
    {
      value: false,
      label: '否'
    }
  ])

  const { formRef, visible, modalTitle, confirmLoading, open, close, setFormState, resetForm, changeConfirmLoading } =
    useModalForm(formState)

  const treeData = ref<TreeSelectProps['treeData']>([])
  const { loading: organizationOptionsLoading, refresh } = useRequest<any>(teacherManageApi.getOrganizationTree, {
    onSuccess({ data }) {
      const deep = (data: any[]): any[] | null => {
        if (!data) {
          return null
        }
        return data.map((item: any) => {
          return {
            label: item.orgName,
            value: item.id,
            disabled: !(item.isAuthActive && item.level === 5),
            children: deep(item.children)
          }
        })
      }
      treeData.value = deep(data) || []
    }
  })

  const treeSelectChange = () => {
    getLink()
  }

  // 获取邀请链接
  const getLink = async () => {
    const { data } = await studentsManageApi.getLink(
      {},
      {
        urlParams: {
          id: formState.orgId
        }
      }
    )

    showFooter.value = data ? null : undefined

    if (data) {
      Object.assign(formState, {
        id: data?.id,
        orgId: data?.orgId,
        authType: data?.authType
      })

      const link = window.location.origin + '/invite2Join?' + `inviteCode=${data?.inviteCode}`
      inviteLink.value = `邀请你加入${data?.fullOrgName}，${link}`
    } else {
      inviteLink.value = ''
      Object.assign(formState, {
        id: undefined
      })
    }
  }

  watch(
    () => visible.value,
    val => val && refresh()
  )

  const onClose = () => {
    showFooter.value = undefined
    close()
    emits('close')
  }

  const { runAsync: runCreateInviteLink } = useRequest<any>(studentsManageApi.createInviteLink)
  const onSubmit = async () => {
    try {
      changeConfirmLoading(true)
      await formRef.value?.validate()
      await runCreateInviteLink(formState)
      getLink()
      message.success('操作成功')
      emits('submit', formState)
    } catch (error) {
      console.error(error)
    } finally {
      changeConfirmLoading(false)
    }
  }

  // 更改审核状态
  const authTypeChange = async (e: any) => {
    const value = e.target.value
    if (!formState.id) {
      return
    }
    await studentsManageApi.updateInviteInfo({ id: formState.id, authType: value })
    await getLink()
    message.success('操作成功')
  }

  // 失效链接
  const { loading: inviteLinkLoading, runAsync: runDelInviteLink } = useRequest<any>(studentsManageApi.delInviteLink)
  const handleInvalid = async () => {
    await runDelInviteLink({}, { urlParams: { id: formState.id } })
    message.success('操作成功')
    getLink()
  }

  // 复制链接
  const copyLink = () => {
    copyText(inviteLink.value)
    message.success('复制成功')
  }

  defineExpose({
    open,
    close,
    setFormState,
    resetForm,
    changeConfirmLoading
  })
</script>

<style lang="less" scoped>
  .invitation-card-wrap {
    padding: 20px 32px 16px;
    background: #fff;
    box-shadow: 0 -1px 4px 0 rgba(2, 36, 59, 0.06);

    .header {
      display: flex;
      justify-content: space-between;

      .title-wrap {
        display: flex;
        align-items: center;
        gap: 0 4px;

        > p {
          font-size: 16px;
          color: rgba(21, 23, 27, 0.95);
          font-weight: 700;
          line-height: 24px;
        }

        .tag-wrap {
          width: 36px;
          height: 22px;
          font-size: 12px;
          text-align: center;
          color: #4fb35b;
          background: rgba(79, 179, 91, 0.08);
          font-weight: 500;
          line-height: 22px;

          &.invalid {
            color: #bdbdbd;
            background: rgba(189, 189, 189, 0.08);
          }
        }
      }
    }

    .content-wrap {
      padding: 12px 16px;
      margin-top: 8px;
      font-size: 14px;
      color: rgba(17, 22, 31, 0.75);
      background: #f7f7f7;
      border-radius: 6px;
      font-weight: 400;
      line-height: 22px;
    }
  }
</style>
